package familytree.yu.com.sso.config;

import familytree.yu.com.sso.constants.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @Author: yuyunbo
 * @Date: 2021/2/23 20:43
 * @Description:
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder initBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }



    /**
     * 配置用户登录验证服务
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin().loginPage(Constants.LOGIN_PAGE).loginProcessingUrl(Constants.LOGIN_PROCESSING_URL).failureForwardUrl(Constants.LOGIN_ERROR)
                //允许访问
                .and()
                .authorizeRequests().antMatchers(
                "/user/**",
                Constants.LOGIN_PROCESSING_URL,
                Constants.LOGIN_PAGE,
                Constants.AFTER_LOGING_PAGE,
                Constants.LOGIN_ERROR,
                "/css/**","/lib/**","/images/**","/js/**","/font/**").permitAll().anyRequest().authenticated()
                //禁用跨站伪造
                .and().csrf().disable();

    }


    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/doc.html", "/v2/**");
    }


}
